package day06homework;

import java.util.Arrays;

public class Day06HomeWork {

	public static void main(String[] args) {
		int[] oldArr = {1,3,4,5,6,6,0,5,6,7,0,5};
		int[] noZeroArr = getNoZeroArr(oldArr);
		
		System.out.println(Arrays.toString(noZeroArr));
		
		
		int[] arr1 = {1,7,9,11,13,15,17,19};
		int[] arr2 = {2,4,6,8,10};
		int[] mergeAndSort = mergeAndSort(arr1, arr2);
		System.out.println(Arrays.toString(mergeAndSort));
		
		
	}
	/**
	 * ⑤定一个求多个整数积的方法（使用可变参数完成）;
	 */
	public int getProduct(int... arr){
		int product = 1;
		for (int i = 0; i < arr.length; i++) {
			product *= arr[i];
		}
		return product;
	}
	
	/**
	 * ②现有如下的数组
		  int[] oldArr = {1,3,4,5,6,6,0,5,6,7,0,5};
		  取出以上数组不为0的值，然后将不为0的值存入一个新的数组，生成新的数组为：
		  int[] newArr = {1,3,4,5,6,6,5,6,7,5}; 通过一个方法实现
	*/	
	public static int[] getNoZeroArr(int[] arr){
		if (arr == null) {
			return null;
		}
		
		//确定新数组长度，遍历老数组，计数不为零的元素个数
		int count = 0;
		for (int i : arr) {
			//将不为零的个数+1
			if (i != 0) {
				count++;
			}
		}
		
		//创建新数组
		int[] newArr = new int[count]; 
		
		int index = 0;//声明变量表示新数组下标
		for (int i = 0; i < arr.length; i++) {
			//判断当前遍历到的元素，如果不是0，则向新数组复制
			if (arr[i] != 0) {
				newArr[index] = arr[i];
				index++;
			}
		}
		//循环结束，将新数组返回
		return newArr;
	}
	
	
	
	/**
	 * 	  ③现在给出两个数组
		 数组arr1: “1,7,9,11,13,15,17,19”;   
		 数组arr2:”2,4,6,8,10”			
		两个数组合并之后数组arr，在按照升序排列;通过定义方法实现
	 */
	public static int[] mergeAndSort(int[] arr1,int[] arr2) {
		//后面会讲
		if (arr1 == null || arr2 == null) {
			throw new IllegalArgumentException("非法参数！");
		}
		//创建新数组
		int[] newArr = new int[arr1.length + arr2.length];
		//复制第一个数组arr1中元素到新数组
		for (int i = 0; i < arr1.length; i++) {
			newArr[i] = arr1[i];
		}
		
		//复制第2个数组arr2中元素到新数组
		for (int i = 0; i < arr2.length; i++) {
			newArr[arr1.length+i] = arr2[i];
		}
		
		//排序
		Arrays.sort(newArr);
		return newArr;
	}
	
}
